import { APlugin } from '../types/common.interface';
import { Inject, Injectable, PluginInjectable } from '../decorators/inject';
import { ValueChangeCommand, IValue } from '../commands/value-change.command';
import { TableDatas } from '../cors/table-datas';
import { ExecuteRecord } from '../cors/execute-record';
import { RenderTrigger } from '../cors/render-trigger';
import { IValueChangePlugin } from './value-change.plugin.interface';

@Injectable('ValueChangePlugin')
@PluginInjectable('ValueChangePlugin')
export class ValueChangePlugin extends APlugin implements IValueChangePlugin{
  static pluginName = 'ValueChangePlugin';
  constructor(
    protected datas: TableDatas,
    protected executeRecord: ExecuteRecord,
    protected renderTrigger: RenderTrigger,
  ) {
    super();
  }

  public updateCellValue(row: number, col: number, value: BaseValueType) {
    let values: IValue[] = [{ row, col, value }];
    this.excutCommand(values);
  }

  public updateCellValues(values: { row: number, col: number, value: BaseValueType }[]) {
    this.excutCommand(values);
  }

  public clearValue(position: TRange) {
    let values: IValue[] = [];
    let maxRow = position.rowspan === -1 ? this.datas.getMaxRow() + 1 : position.row + position.rowspan;
    for (let row = position.row; row < maxRow; row++) {
      let rowInstance = this.datas.getRow(row);
      let maxCol = position.colspan === -1 ? rowInstance.getMaxCol() + 1 : position.col + position.colspan;
      for (let col = position.col; col < maxCol; col++) {
        values.push({
          row: row,
          col: col,
          value: null
        });
      }
    }
    this.excutCommand(values);
  }

  public copyTo(from: TRange, to: TRange) {
    throw new Error('not impletment!');
  }

  protected excutCommand(values: IValue[]): void {
    let command = new ValueChangeCommand(this.datas, values);
    this.executeRecord.execute(command);
  }

  public init() {

  }
  public destroy() {

  }
}